<?php
namespace app\front\service;
use app\front\model\Store as StoreModel;
use app\front\model\Shop as ShopModel;
use app\front\model\Account as AccountModel;
use app\front\model\Filiale as FilialeModel;
use app\front\model\Discount as DiscountModel;
use app\front\model\Award as AwardModel;
class BasePayService extends GetMsgService
{
    public function getPrepayId($out_trade_no,$moneyNum){
        //调用统一下单方法
        $arr = $this->unifiedOrder($out_trade_no,$moneyNum);
        // 获取其中的订单ID
        return $arr['prepay_id'];
    }
    public function award_prob($store_id,$customer_id,$money,$mch_billno){
       // $money=10;
        $store_data =  StoreModel::where('id='.$store_id)->find();
        //获取商铺信息
        $shop_data =  ShopModel:: where('id='.$store_data['shop_id'])->find();
        //获取分公司信息
        $filiale_data = FilialeModel::where('id='.$shop_data['filiale_id'])->find();
        //获取中奖概率
        $award_data = AwardModel::where('filiale_id='.$filiale_data['id'])->find();
        if($award_data==null){
            $award_data = AwardModel::where('filiale_id=0')->find();
        }
        logs("AWARD.TXT", $award_data);
        //获取具体折扣概率
        $discount_data = DiscountModel::where('shop_id is null and filiale_id='.$filiale_data['id'])->find();
        if($discount_data==null){
            $discount_data = DiscountModel::where('shop_id is null and filiale_id=0')->find();
        }
        //获取返还红包比例
        $account_data =  AccountModel::where('shop_id='.$shop_data['id'])->find();
        if($account_data==null){
            $account_data =  AccountModel::where('shop_id = 0 and filiale_id = '.$filiale_data['id'])->find();
        }
        $award_percent = $account_data['award_percent'];
        $purpose = 1;
//         if($money>=10){  
            $award_money=0;
            //判断是否中分公司红包
            logs("1data.txt", $award_data);
            logs("3data.txt",  $account_data);
            if(rand(1,100) <= $award_data['prob']){
                //如果中奖了，执行中奖概率算法
                $sum = 100;
                $arr = array(array(0,$discount_data['prob1']),array(rand(1,20),$discount_data ['prob2']),array(rand(21,80),$discount_data['prob3']),array(rand(81,bcsub(100, $award_percent,2)),$discount_data['prob4']));
                for($i = 0;$i<count($arr);$i++){
                    if(rand(0,$sum)<=$arr[$i][1]){
                        $award_money = bcdiv(bcmul($money,bcsub(100,$arr[$i][0],2)),100,2);
                        break;
                    }else{
                        $sum = bcsub($sum,$arr[$i][1],2);
                    }
                }
             
                if($filiale_data['hbmoney']>=$award_money){
                    $purpose = 3;
                }else{
                    $purpose = 1;
                    $award_money = bcmul($money,bcdiv($award_percent,100,3),3);
                    $award_money =  $this->getFloatBaseRadPack($award_money,$filiale_data['float_red_pack']);
                }
            }else{
                $shop_discount_data = DiscountModel::where('shop_id',$shop_data['id'])->find();
                logs("2data.txt", $shop_discount_data);
                if($shop_discount_data==null){
                    $shop_discount_data = DiscountModel::where('shop_id',0)->find();
                }
                $shop_discount_data=json_decode($shop_discount_data,true);
                $sum2 = 100;
                $award_money  = 0;
                $arr2 = array(array(0,$shop_discount_data['prob1']),array(rand(1,20),$shop_discount_data ['prob2']),array(rand(21,80),$shop_discount_data['prob3']),array(rand(81,bcsub(100, $award_percent,2)),$shop_discount_data['prob4']));
                for($i = 0;$i<count($arr2);$i++){
                    if(rand(0,$sum2)<=$arr2[$i][1]){
                        $award_money = bcdiv(bcmul($money,bcsub(100,$arr2[$i][0],2)),100,2);
                        break;
                    }else{
                        $sum2 = bcsub($sum2,$arr2[$i][1],2);
                    }
                }
                logs("1award.txt", $award_money);
              //  if($shop_data['shop_hb_money']<$award_money||$award_money==0){
                    $purpose = 1;
                    $award_money = bcmul($money,bcdiv($award_percent,100,3),3);
                    $award_money =  $this->getFloatBaseRadPack($award_money,$filiale_data['float_red_pack']);
//                 }else{
//                     $purpose = 4;
//                 }
            }
            //如果红包金额大于红包金额上限则发基本包
            if($award_money>$award_data['maxmoney']){
            $award_money = bcmul($money,bcdiv($award_percent,100,3),3);
            $award_money =  $this->getFloatBaseRadPack($award_money,$filiale_data['float_red_pack']);
        }

        $record_statu=0;
        if(  $award_money>0){
            $record_statu=1;
        }
        //插入中奖纪录
        $record_data = ['mch_billno'=>$mch_billno,'customer_id'=>$customer_id,'shop_id'=>$shop_data['id'],'filiale_id'=>$filiale_data['id'],'store_id'=>$store_id,'order_money'=>$money,'award_money'=>$award_money,'create_time'=>date("Y-m-d H:i:s",time ()),'record_statu'=>$record_statu,'purpose'=>$purpose];
        //AwardrecordModel::create($record_data);
        //返回返还红包金额
        return  $record_data;
    }
    
    public function unifiedOrder($out_trade_no,$moneyNum){
        /**
         * 1.构建原始数据
         * 2.加入签名
         * 3.将数据转换为XML
         * 4.发送XML格式的数据到接口地址
         */
        //1.构建原始数据
        
        $params = [
            'appid'=> config('appid'),//公众号ID
            'mch_id'=> config('mch_id'),//商户号
            'nonce_str'=>md5(time()),//随机字符串
            'body'=>'向至富通合作商家付款',//商品描述
            'out_trade_no'=>$out_trade_no,//内部订单号
            'total_fee'=>$moneyNum,  //总价
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],//客户端IP
            'notify_url'=>config('NOTIFY') ,//支付通知URL
            'trade_type'=>'JSAPI',//支付类型
            'product_id'=>$out_trade_no,//商品ID 非比传选项
            'openid'    => $this->getOpenId()
        ];
        //2.加入签名
        $params = setSign($params);
        //3.将数据转换为XML
        $xmldata = ArrToXml($params);
        // 4.发送XML格式的数据到接口地址
        $resdata = postStr(config('UOURL'), $xmldata);
        $arr = XmlToArr($resdata);
        logs('unifiedOrderReturn.txt',  $resdata);
        return $arr;
    }


    /**
    
    * 函数用途描述:获取微信公众号支付的JS参数列表
    
    * @param: $prepay_id->预支付ID
    
    * @return:返回JS字符串
    
    */
    public function getJsGzhParams($prepay_id){
        $params = [
            'appId' => config("appid"),
            'timeStamp' => strval(time()),//将时间戳转换为字符（防止苹果手机报错说缺少此参数）
            'nonceStr' => md5(time()),
            'package' =>'prepay_id=' . $prepay_id,//预支付ID
            'signType' =>'MD5',
            //       'paySign' => $this->getSign($params)
        ];
        $params['paySign'] = getSign($params);
        $json= json_encode($params);
        return $json;
    }
    
    public function getArrGzhParams($prepay_id){
        $params = [
            'appId' => config("appid"),
            'timeStamp' => strval(time()),//将时间戳转换为字符（防止苹果手机报错说缺少此参数）
            'nonceStr' => md5(time()),
            'package' =>'prepay_id=' . $prepay_id,//预支付ID
            'signType' =>'MD5',
            //       'paySign' => $this->getSign($params)
        ];
        $params['paySign'] = getSign($params);
      //  $json= json_encode($params);
        return $params;
    }
    
    
   
    
    
}

